import { defineStore } from 'pinia'
import { ElMessageBox } from 'element-plus'
import userApi from '@/apis/user'
import { getStorageUrl } from '@/utils/utils'
import { useConfigStore } from './config'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null, // User object
    isAuthenticated: false, // Is user authenticated
    token: null, // User token
  }),
  actions: {
    setAuth(data) {
      this.setUser(data.user)
      this.setToken(data.token)
    },
    /**
     * Login user
     * @param data
     */
    setUser(user) {
      this.user = user
    },

    setToken(token) {
      this.token = token.token
      this.isAuthenticated = true
      localStorage.setItem('token', this.token)
    },

    /**
     * Logout user
     */
    clear() {
      this.user = null
      this.token = null
      this.isAuthenticated = false
      localStorage.removeItem('token')
    },

    /**
     * Check user authentication
     * @returns {Promise<void>}
     */
    async check() {
      const token = localStorage.getItem('token')
      if (token) {
        try {
          // 假设有一个验证令牌的端点
          const { data } = await userApi.passport.verifyToken()
          this.user = data
          this.token = token
          this.isAuthenticated = true
        } catch (error) {
          console.error('Token verification failed:', error)
          this.clear()
        }
      }
    },

    authOrLogin(authCallback, loginOptions) {
      if (this.isAuthenticated) {
        authCallback()
      } else {
        const { router, options } = loginOptions
        this.toLogin(router, options)
      }
    },

    toLogin(router, options = {}) {
      const redirect = () => {
        router.push({
          name: options?.routeName ?? 'authLogin',
          query: { redirect: encodeURIComponent(options?.redirect ?? '') },
        })
      }
      if (options?.confirm) {
        ElMessageBox.confirm(
          options?.message ?? '您需要先登录或注册，才能操作，是否登录或注册？',
          options?.title ?? '提示',
          {
            type: 'warning',
          }
        ).then(() => redirect())
      } else {
        redirect()
      }
    },

    getAvatar() {
      let avatar = this.user?.avatar
      if (!avatar) {
        const configStore = useConfigStore()
        avatar = getStorageUrl(configStore.get('user.avatar'))
      }
      return avatar
    },
  },
})
